//
//  HMTabBar.swift
//  weibo
//
//  Created by 杨念川 on 16/8/29.
//  Copyright © 2016年 杨念川. All rights reserved.
//

import UIKit

class HMTabBar: UITabBar {
    //设置闭包
    var composeButtonClosure: (() -> ())?
    //重新init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //初始化UI
    func setupUI() {
        backgroundImage = #imageLiteral(resourceName: "tabbar_background")
        addSubview(composeButton)
        
    }
    //重写layoutSubViews
    override func layoutSubviews() {
        super.layoutSubviews()
        //调整composeButton的位置
        composeButton.center = CGPoint(x: self.frame.width * 0.5, y: self.frame.height * 0.5)
        //求出每个按钮的宽度
        let itemW = UIScreen.main.bounds.width / 5
        //定义一个当前按钮的索引
        var index = 0
        //遍历subViews
        for subView in self.subviews {
            //判断subViews是都包含uibutton
            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
                print(subView)
                //计算item的x和y
                let itemx = CGFloat(index) * itemW
                //调整按钮的宽度
                subView.frame.size.width = itemW
                //调整按钮的x
                subView.frame.origin.x = itemx
                //按钮的索引自增
                index = index + 1
                //如果按钮的索引为2，则再往右移动一个位置
                if index == 2 {
                    index = index + 1
                }
            }
        }
    }
    //composeButtonClick点击事件
    @objc private func composeButtonClick() {
        composeButtonClosure?()
    }
    //懒加载
    lazy var composeButton: UIButton = {
        let button = UIButton()
        //设置按钮背景图标
        button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: UIControlState.normal)
        button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        //设置按钮图标
        button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: UIControlState.normal)
        button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        //设置按钮大小
        button.sizeToFit()
        //添加点击事件
        button.addTarget(self, action: #selector(composeButtonClick), for: .touchUpInside)
        return button
    }()
}
